package dataStructure.Sort;

public class BubbleSort {
    public static void bubbleSort(int[] nums) {
        //一轮冒泡过程
        for (int j = 0; j < nums.length - 1; j++) {
            for (int i = 0; i < nums.length - 1 - j; i++) {
                if (nums[i] > nums[i + 1]) {
                    int tem = nums[i];
                    nums[i] = nums[i + 1];
                    nums[i + 1] = tem;
                }
            }
        }
    }

    //剪枝版本
    //用swapped来标记这轮还有没有进行交换操作,如果每次都是nums[i]<nums[i+1],说明此时数组已经有序
    public static void betterBubbleSort(int[] nums) {
        //一轮冒泡过程
        for (int j = 0; j < nums.length - 1; j++) {
            boolean swapped = false;
            for (int i = 0; i < nums.length - 1 - j; i++) {
                if (nums[i] > nums[i + 1]) {
                    swapped = true;
                    int tem = nums[i];
                    nums[i] = nums[i + 1];
                    nums[i + 1] = tem;
                }
            }
            if (!swapped) break;
        }
    }
}
